<script setup lang="ts">
import useMenuStore from '@/store/menu/menu'

import { reactive, ref } from 'vue'

const menuStore = useMenuStore()

// 1.定义内部的属性
const formData = reactive<any>({
  name: '',
  type: '',
  url: '',
  sort: '',
  parentId: '',
  icon: ''
})

// 3.显示弹窗的方法
const centerDialogVisible = ref(false)
// 显示密码框
const isShowPsW = ref(true)
// 编辑用户的信息
const editData = ref<any>()
const showModel = (isNew: boolean = true, itemData?: any) => {
  // 1.显示弹窗
  centerDialogVisible.value = true

  // 2.是否显示密码框
  isShowPsW.value = isNew

  if (!isNew && itemData) {
    //当isNew等于false并且itemData有值就是编辑用户

    // 3.编辑用户
    for (const key in formData) {
      formData[key] = itemData[key]

      // 4.存储编辑用户的信息
      editData.value = itemData
    }
  } else {
    // 5.编辑用户
    for (const key in formData) {
      formData[key] = ''
    }
  }
}

// 4.确定逻辑
const handleConfirmClick = () => {
  // 关闭弹窗
  centerDialogVisible.value = false

  if (!isShowPsW.value && editData.value) {
    // 编辑用户
    const id = editData.value.id
    menuStore.editMenuDataAction(id, formData)
  } else {
    // 新建用户
    menuStore.createMenuDataAction(formData)
  }
}

// 暴露事件
defineExpose({ showModel })
</script>

<template>
  <div class="user-model">
    <el-dialog
      v-model="centerDialogVisible"
      :title="isShowPsW ? '新建菜单' : '编辑菜单'"
      width="30%"
      center
    >
      <el-form :model="formData" label-width="80px" size="large">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单级别" prop="type">
          <el-input type="number" v-model="formData.type" placeholder="请输入菜单级别" />
        </el-form-item>
        <el-form-item label="菜单icon" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入菜单icon" />
        </el-form-item>

        <el-form-item label="菜单url" prop="url">
          <el-input v-model="formData.url" placeholder="请输入菜单url" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.user-model {
}
</style>
